<?php
namespace app\member\model;

use think\Model;
use think\Db;

class MemberAddress extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'xb_member_address';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 获取下单时会员地址 sky
    public function getAddress($mid,$limit=5)
    {
        $mid = intval($mid);
        if($mid==0) return false;
        $list = $this->where('member_id',$mid)->order('is_default', 'desc')->limit($limit)->select();
        $list = $list ? collection($list)->toArray() : array();
        return $list;
    }

    //设置默认收货地址 sky
    public function setDefaultAddress($mid,$addr_id)
    {
        $addr_id = intval($addr_id);
        if($mid==0 || $addr_id==0) return false; 
        $result = Db::transaction(function()use($mid,$addr_id){
            $this->where('member_id',$mid)->update(['is_default'=>0]);
            $where = ['member_id'=>$mid,'addr_id'=>$addr_id];
            $rs = $this->where($where)->update(['is_default'=>1]);
            return $rs;
        });
        return $result;
    }

    //增加收货地址 sky
    public function createAddress($data=array())
    {
        if(!is_array($data) || empty($data['consignee']) || empty($data['province']) || empty($data['city']) || empty($data['area']) || empty($data['address'])) return false;
        $this->save($data);
        return $this->addr_id;
    }

    //返回一条地址数据 sky
    public function getOne($addr_id)
    {
        $id = intval($addr_id);
        if($id==0) return false;
        $data = self::get($id);
        return is_object($data) ? $data->toArray() : array();
    }

    //搜索地址
    public function search($mid,$kw)
    {
        
        $kw = trim($kw);
        //if(empty($kw)) return false;

        $where = "member_id={$mid}";
        if($kw){
            $where .= " and (consignee like '%s' or mobile='%s')";
            $where = sprintf($where, "%{$kw}%", $kw);
        }
        $data = $this->where($where)->order('is_default', 'desc')->select();
        
        return $data;
    }
    public static function getAddressInfo($map=[]){

        $data_list = self::view('member_address', true)
            ->view('member','name,id','id=member_address.member_id','left')
            ->where($map)
            ->order('addr_id desc')
            ->paginate();
        return $data_list;
    }

    //修改当前用户所有默认收货地址
    public static function setAllDefault($mid = 0){
        $mid = intval($mid);
        $result = self::where('member_id', $mid)->update(['is_default' => '0']);
        return $result;
    }

    //删除
    public function del($mid,$addr_id){
        $addr_id = intval($addr_id);
        if($mid==0 || $addr_id==0) return false; 
        $result = Db::name('member_address')->where(['addr_id' => $addr_id, 'member_id' => $mid])->update(['is_del' => '1']);
        return $result;
    }
}